<template>
    <!-- 日历热点图容器 -->
    <div id="calendar" class="overflow-hidden w-full h-60 object-center"></div>
</template>

<script setup>
import * as echarts from 'echarts'
import { onMounted, watch } from 'vue'
import { format, subMonths, subYears } from 'date-fns';

// 对组件外暴露指定变量值
const props = defineProps({
    value: {
        type: Object,
        default: null
    }
})

// 获取当前日期
const currentDate = new Date()
// 1年前
const oneYearAgo = subYears(currentDate, 1)

//  格式化的开始与结束
const startDate = format(oneYearAgo, "yyyy-MM-dd")
const endDate = format(currentDate, "yyyy-MM-dd")

// 日历数据
const myPublishArticleDateForOneYearData = []

// 初始化日历热点图
const initCalender = () => {
    // 将数据设置到数组中
    let map = props.value
    for (let key in map) {
        if (map[key] > 0) console.log(key)
        myPublishArticleDateForOneYearData.push([
            key,
            map[key]
        ]);
    }
    let chartDom = document.getElementById('calendar');
    let myChart = echarts.init(chartDom);
    let option;

    option = {
        title: {
            top: 5,
            left: 'center',
            text: '未见花闻个人博客平台 近一年内文章贡献图'
        },
        visualMap: {
            show: false,
            min: 0,
            max: 16
        },
        calendar: {
            range: [startDate, endDate]
        },
        series: {
            type: 'heatmap',
            coordinateSystem: 'calendar',
            data: myPublishArticleDateForOneYearData
        },
        gradientColor: [
            // 自定义热点颜色，参考了 GitHub 代码提交的颜色
            '#fff',
            '#40c463',
            '#30a14e',
            '#216e39',
        ]
    };

    option && myChart.setOption(option);
}

// 监听value 当value变化时初始化图
watch(() => props.value, () => initCalender())
</script>